﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using NDatabase;

namespace ConsoleApplication2
{
    public static class DbGateWay
    {
        const string dbFileName = "ndb.db";

        public static void StoreList<T>(List<T> itemList) where T : class
        {
            using (var odb = OdbFactory.Open(dbFileName))
            {
                foreach (T item in itemList)
                {
                    var q = odb.QueryAndExecute<T>().Where(x => x.Equals(item));
                    int count = q.Count(x => true);
                    if (count == 0) odb.Store<T>(item);
                }
            }
        }

        public static void Store<T>(T item) where T : class
        {
            using (var odb = OdbFactory.Open(dbFileName))
            {
                var q = odb.QueryAndExecute<T>().Where(x => x.Equals(item));
                int count = q.Count(x => true);
                if (count == 0) odb.Store<T>(item);
            }
        }

        public static void Retrieve<T>(out List<T> returnItem, Expression<Func<T, bool>> predicate)
        {
            using (var odb = OdbFactory.Open(dbFileName))
            {
                var q = odb.AsQueryable<T>().Where(predicate);
                returnItem = q.ToList<T>();
            }
        }
    }
}